/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import conn.EMIS4Connection;
import dao.PersonDao;
import dialog.ConfirmationDialog;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.JOptionPane;
import main.MainFrame;
import obj.Person;
import panels.PersonPanel;

/**
 *
 * @author jm1156
 */
public class DashboardUtil {

  /**
   *
   */
  public static boolean searchForPatient() {
    PersonPanel personPanel = new PersonPanel();
    PersonRequested personRequested = PersonRequested.getInstance();
    ConfirmationDialog confirmationDialog = new ConfirmationDialog(null, personPanel, true);
    EMIS4Connection connection = EMIS4Connection.getInstance();
    PersonDao personDao = new PersonDao();
    Person person;
    List<Person> persons;
    boolean personAdded = false;

    //show the window and wait for input
    confirmationDialog.setLocationRelativeTo(MainFrame.getInstance());
    confirmationDialog.setVisible(true);
    Calendar cal = new GregorianCalendar();
    while (!personAdded && confirmationDialog.okPressed()) {

      personPanel = (PersonPanel) confirmationDialog.getPanel();
      person = personPanel.getPopulatedPerson();

      //means that they didn't change the date
      if (DateUtils.matchCurrentDate(person.getDOB())) {
        person.setDOB(null);
      }
      persons = null;
      try {
        connection.connect();
        persons = personDao.searchMatching(connection.getConnection(), person);
      } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "There was an error searching for the patient", "Unexpected Error", JOptionPane.ERROR_MESSAGE);
        confirmationDialog.setVisible(true);
        continue;
      }

      if (persons == null || persons.size() == 0) {
        JOptionPane.showMessageDialog(null, "No patients were found with the search.", "No Patients Found", JOptionPane.ERROR_MESSAGE);
        confirmationDialog.setVisible(true);
        continue;
      } else if (persons.size() > 1) {
        JOptionPane.showMessageDialog(null, "More than one patient was found.", "Many Patients Found", JOptionPane.ERROR_MESSAGE);
        confirmationDialog.setVisible(true);
        continue;
      } else {
        personRequested.setPerson(persons.get(0)); //should only be one since the other checks for multiple or none
        personAdded = true;
      }
    }
    return personAdded;
  }

  public static void main(String[] args) {
    DashboardUtil.searchForPatient();
    PersonRequested requested = PersonRequested.getInstance();
    System.out.println("Requested: " + requested.getPerson());
  }
}
